package com.example.backend.controller.category;

import cn.hutool.core.convert.Convert;
import com.example.backend.dto.request.CategoryDto;
import com.example.backend.entitly.mysql.classify.Categories;
import com.example.backend.enums.ResultCodeEnum;
import com.example.backend.service.mysql.classify.CategoriesService;
import com.example.backend.utils.ResultJson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/comment")
@Tag(name = "分类管理")
public class CategoryController {

    private final CategoriesService categoriesService;

    @Operation(summary = "创建分类", description = "创建分类")
    @PostMapping("/create")
    public ResultJson<?> createCategory(@RequestBody CategoryDto categoryDto) {
        Categories categories = Convert.convert(Categories.class, categoryDto);
        boolean b = categoriesService.save(categories);
        if (!b) {
            return ResultJson.fail(ResultCodeEnum.CATEGORY_CREATE_FAIL.getCode(), ResultCodeEnum.CATEGORY_CREATE_FAIL.getMessage());
        }
        return ResultJson.ok();
    }

    @Operation(summary = "删除分类", description = "删除分类")
    @PostMapping("/delete")
    public ResultJson<?> deleteCategory(Integer categoryDto) {
        for (Categories categories1 : categoriesService.getChildrenByParentId(categoryDto)) {
            categoriesService.removeById(categories1.getCategoryId());
        }
        categoriesService.removeById(categoryDto);
        return ResultJson.ok();
    }

    @Operation(summary = "更新分类", description = "更新分类")
    @PostMapping("/update")
    public ResultJson<?> updateCategory(@RequestBody CategoryDto categoryDto) {
        Categories categories = Convert.convert(Categories.class, categoryDto);
        boolean b = categoriesService.updateById(categories);
        if (!b) {
            return ResultJson.fail(ResultCodeEnum.CATEGORY_UPDATE_FAIL.getCode(), ResultCodeEnum.CATEGORY_UPDATE_FAIL.getMessage());
        }
        return ResultJson.ok();
    }
}
